package com.singleton.type1;

/**
 * 单列模式
 * 饿汉式
 */
public class SingletonTest01 {

    public static void main(String[] args) {
        //测试
        Singleton instance = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        //获取到的两个实例对象是同一个对象
        System.out.println(instance == instance2); //true
        //hashCode值也是相同的
        System.out.println("instance.hashCode() = " + instance.hashCode());
        System.out.println("instance.hashCode() = " + instance2.hashCode());

    }
}

//饿汉式(静态变量)
class Singleton {

    //2.本类内部创建一个对象实例
    private final static Singleton instance = new Singleton();

    //1.构造器私有化,外部能new
    private Singleton() {


    }

    //3.对外提供一个公有的静态方法,返回实例对象
    public static Singleton getInstance() {
        return instance;
    }

}
